Async = require 'async'
Commodity = require './commodity'
_ = require 'underscore'
Fs = require 'fs'

viewDataHandler = 
  ###*
   * [home description]
   * @param  {[type]} cbf [description]
   * @return {[type]}     [description]
  ###
  home : (query, options, cbf) ->
    query = query || {}
    Async.parallel {
      total : (cbf) ->
        Commodity.count query, cbf
      data : (cbf) ->
        Commodity.find query, options, cbf
    },
    (err, results) ->
      cbf err, results

  commodity : (id, cbf) ->
    Commodity.find {_id : id}, cbf

  commodityModify : (id, data, cbf) ->
    Commodity.findByIdAndUpdate id, data, cbf
  table : (cbf) ->
    Commodity.find {}, cbf

autoAddTag = (key, tag) ->
  Commodity.find {}, null, (err, data) ->
    docs = []
    _.each data, (item) ->
      if item.title.indexOf(key) != -1
        item = item.toObject()
        if _.indexOf(item.tags, tag) == -1
        # if true
          # item.tags = ['美赞臣', '奶粉']
          item.tags.push tag
          item.modifiedTime = new Date()
          id = item._id
          delete item._id
          delete item.__v
          if !item.pics
            delete item.pics
    
          Commodity.findByIdAndUpdate id, item, (err) ->
            console.log item
            console.log err
autoAddTag '太古', '太古'


getAllItems = () ->
  Commodity.find {}, null, (err, data) ->
    docs = []
    _.each data, (item) ->
      item = item.toObject()
      delete item._id
      delete item.__v
      docs.push item

    saveData = JSON.stringify docs
    Fs.writeFile '/Users/vicanso/workspace/tmp/data.json', saveData, (err) ->
      console.log "err:#{err}"
# getAllItems()


# checkCode = () ->
#   Commodity.find {}, null, (err, data) ->
#     docs = []
#     _.each data, (item) ->
#       item = item.toObject()
#       barcode = global.parseInt item.barcode
#       if global.isNaN barcode
#         id = item._id
#         item.eachPackTotal = item.package
#         item.package = item.barcode
#         item.barcode = ''
#         delete item._id
#         delete item.__v    
#         if !item.pics
#           delete item.pics
#         if !item.eachPackTotal
#           delete item.eachPackTotal
#         Commodity.findByIdAndUpdate id, item, (err) ->
#           console.log item
#           console.log err
# checkCode()
module.exports = viewDataHandler
